import forge from 'node-forge'
import { getPublicKey, setPublicKey } from '@/utils/publicKey'
import { getKey } from '@/api/key'
/**
 * @description:
 * @param {*} 图片文件名称
 * @return {*} 图片url地址
 */

export const getImage = (imgUrl) => {
  return new URL(`../assets/image/${imgUrl}`, import.meta.url).href
}

/**
 * @description: 将需要加密的内容通过公钥进行加密
 * @param {*} publicKey 公钥
 * @param {*} value  需要加密的值
 * @return {*}  加密后的值
 */
export const formatPem = (pemKey) => {
  // 确保 PEM 头部和尾部存在
  if (
    !pemKey.startsWith('-----BEGIN PUBLIC KEY-----') &&
    !pemKey.startsWith('-----BEGIN RSA PUBLIC KEY-----')
  ) {
    pemKey = '-----BEGIN PUBLIC KEY-----\n' + pemKey + '\n-----END PUBLIC KEY-----'
  }
  return pemKey
}

export const encrypt = async (value) => {
  let key = getPublicKey()
  try {
    if (!key || key === 'undefined') {
      const result = await getKey()
      key = result.data.key
      key = key.replace(/\. +/g, '')
      key = key.replace(/[\r\n]/g, '')
      setPublicKey(key)
    }
    const publicKeyPem = formatPem(key) // 确保格式正确
    const publicKey = forge.pki.publicKeyFromPem(publicKeyPem)
    const encrypted = publicKey.encrypt(forge.util.encodeUtf8(value), 'RSA-OAEP')
    return forge.util.encode64(encrypted)
  } catch (err) {
    console.log(err)
  }
}
